package com.yaosheng.thread.jvm;

import java.io.*;

/**
 * Created by yaosheng on 2021/7/8.
 * 自定义ClassLoader
 */
public class MSBClassLoader extends ClassLoader {

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException{

        File f = new File ("/Download/",name.replaceAll (".","/").concat (".class"));
        try{
            FileInputStream fis = new FileInputStream (f);
            ByteArrayOutputStream baos = new ByteArrayOutputStream ();
            int b = 0;

            while((b = fis.read ()) != 0){
                baos.write (b);
            }

            byte[] bytes = baos.toByteArray ();
            baos.close ();
            fis.close ();

            return defineClass (name,bytes,0,bytes.length);
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return super.findClass (name);   //throw ClassNotFoundException
    }

    public static void main(String[] args) throws Exception {

        ClassLoader l = new MSBClassLoader ();
        Class clazz = l.loadClass ("com.yaosheng.thread.jvm.Hello");
        Hello h = (Hello)clazz.newInstance ();
        h.m ();

        System.out.println (l.getClass ().getClassLoader ());
        System.out.println (l.getParent ());
    }
}
